from flask import Flask,request,render_template

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'


@app.route('/greet/<name>')
def greet(name):
    return f'Hello, {name}!'

@app.route('/submit', methods=['POST'])
def submit():
    username = request.form.get('username')
    return f'Form submitted by {username}!'


@app.route('/search/')
def search():
    query = request.args.get('wd')
    return f'Search results for: {query}'



@app.route('/message')
def message():
    return 'This is a simple message.'


@app.route('/hello/<name>')
def hello(name):
    return render_template('hello.html', name=name)




from flask import jsonify

@app.route('/api/data')
def api_data():
    data = {'key': 'value'}
    return jsonify(data)


from flask import Response

@app.route('/custom')
def custom_response():
    response = Response('Custom response with headers', status=200)
    response.headers['X-Custom-Header'] = 'Value'
    return response


from flask import request

@app.route('/info')
def info():
    user_agent = request.headers.get('User-Agent')
    return f'Your user agent is {user_agent}'


from flask import make_response

@app.route('/header')
def custom_header():
    response = make_response('Response with custom header')
    response.headers['X-Custom-Header'] = 'Value'
    return response


@app.route('/divide/<int:x>/<int:y>')
def divide(x, y):
    try:
        result = x / y
        return f'Result: {result}'
    except ZeroDivisionError:
        return 'Error: Division by zero', 400



@app.errorhandler(404)
def not_found(error):
    return 'Page not found', 404


# @app.before_request：在每个请求处理之前运行的函数。
# @app.after_request：在每个请求处理之后运行的函数。
# @app.teardown_request：在请求结束后运行的函数，用于清理工作。


@app.before_request
def before_request():
    print('Before request')

@app.after_request
def after_request(response):
    print('After request')
    return response

@app.teardown_request
def teardown_request(exception):
    print('Teardown request')

@app.route('/status')
def status():
    return 'Everything is OK', 200


from flask import Response

@app.route('/error')
def error():
    return Response('An error occurred', status=500)





if __name__ == '__main__':
    app.run(debug=True)